// 创建用户相关的小仓库
import {defineStore} from 'pinia'
// 引入接口
import {reqLogin, reqLogout, reqRegister, reqUserInfo} from '@/apis/user'
import type {loginFormData, userInfoResponseData} from '@/apis/user/type'
//引入深拷贝方法
//@ts-ignore
// import cloneDeep from 'lodash/cloneDeep'
// 引入工具类
import {GET_TOKEN, REMOVE_TOKEN, SET_TOKEN} from '@/utils/token'

//用于过滤当前用户需要展示的异步路由
/*function filterAsyncRouter(asyncRoutes: any, routes: any) {
    return asyncRoutes.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRouter(item.children, routes)
            }
            return true;
        }
    })
}*/

// 创建用户小仓库
const useUserStore = defineStore('User', {
    // 存储数据
    state: (): { role: string; buttons: any[]; avatarUrl: string; token: string; username: string } => {
        return {
            token: GET_TOKEN(), // 用户的唯一标识
            username: '', // 用户名称
            avatarUrl: '', // 用户头像
            role: '',
            buttons: [], //存储当前用户是否包含某一个按钮
        }
    },
    // 异步|逻辑
    actions: {
        // 用户登录
        async userLogin(data: loginFormData) {
            const result:any = await reqLogin(data)
            if (result.code === 200) {
                this.token = result.data.token
                this.username = result.data.username
                this.avatarUrl = result.data.avatarUrl
                // 2.持久化存储token
                SET_TOKEN(result.data.token)
                // 3.返回登录成功的回调
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        // 获取用户信息
        async userInfo() {
            const result:userInfoResponseData = await reqUserInfo()
            if (result.code === 200) {
                this.username = result.data.username
                this.avatarUrl = result.data.avatarUrl
                this.role = result.data.role
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        // 退出登录
        async userLogout() {
            const result = await reqLogout()
            if (result.code === 200) {
                this.token = ''
                this.username = ''
                this.avatarUrl = ''
                // 清除token
                REMOVE_TOKEN()
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        // 注册用户
        async registerUser(data: any) {
            const result:any = await reqRegister(data)
            if(result.code == 200){
                return 'ok'
            }else{
                return Promise.reject(new Error(result.message))
            }
        }
    },
    // 计算属性
    getters: {

    }
})
// 对外暴露获取小仓库的方法
export default useUserStore;